package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理支付超时的订单
     * 超时十五分钟执行,并且一分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟执行一次
    public void processTimeOutOrder(){
        log.info("处理支付超时的订单{}", LocalDateTime.now());
        //获取十五分钟前的时间
        //todo exam
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //寻找在十五分钟前下单的订单并且状态是未支付的
        List<Orders> list = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT,time);
        //将状态改成取消
        if (list!=null && list.size()>0){
            list.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时,自动取消");
                orderMapper.update(orders);
            });
        }
    }
    /**
     * 处理"派送中"的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("处理派送中的订单{}",new Date());
        //每天凌晨一点处理昨天还在派送中的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//处理一小时前的订单
        List<Orders> list = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (list!=null && list.size()>0){
            //将状态改成已完成
            list.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }
}
